<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Activity as ActivityMdl;
use app\admin\model\Joinactivity;
use app\admin\model\Operator;
use app\admin\model\User;
use app\admin\model\Member;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 活动
 */
class Activity extends BaseController
{

    /**
     * 获取活动列表
     *
     * @return \think\response\Json
     */
    public function getActivityList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId,
            'isDelete' => 2
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = ['in', ['0', $param->villageId]];
        }
        if($param->type == 1){
            // 进行中/未开始
            $where['endTime'] = ['egt', time()];
        }else{
            // 已结束
            $where['endTime'] = ['lt', time()];
        }

        $fields = 'id, title, imgUrl, deadline, createOper, sponsor';
        $model = db('activity');
        $result = $model->where($where)->limit($start, $length)->field($fields)->select();
        $total = $model->where($where)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到活动');
        }

        foreach ($result as &$item) {
            // 参与人数
            $Joinactivitys = Joinactivity::where(['activityId' => $item['id']])->count();
            $item['Joinactivity'] = $Joinactivitys;

            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['createOper']);
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取活动详情
     *
     * @return \think\response\Json
     */
    public function getActivityDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }

        if (empty($param->activityId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'activityId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $activityId = $param->activityId;
        $userId = $param->userId;
        $where = [
            'townId' => $param->townId,
            'id' => $activityId
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = $param->villageId;
        }
        $fields = 'id, title, imgUrl, content, startTime, endTime, address, deadline, quota, createOper, sponsor';

        $model = db('activity');
        $item = $model->where($where)->field($fields)->find();

        if(empty($item)){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关活动');
        }

        $joinactivityDB = db('joinactivity');
        // 报名人员
        /*$joinActivityList = $joinactivityDB->alias('a')->where(['a.activityId' => $activityId])->join('__USER__ u', 'a.userId = u.id')->field('a.createDate,u.avatarUrl as avatar,u.nickName as name,u.memberId')->select();
        if($joinActivityList){
            foreach($joinActivityList as &$value){
                if($value['memberId']){
                    $memberInfo = Member::where(['id' => $value['memberId']])->find();
                    $value['avatar'] = $memberInfo['avatar'];
                    $value['name'] = $memberInfo['name'];
                }
                unset($value['memberId']);
            }
        }*/
        $joinActivityList = $joinactivityDB->where(['activityId' => $activityId])->field('userId,createDate,userAvatar as avatar,userName as name')->select();
        if($joinActivityList){
            foreach($joinActivityList as &$value){
                $value['memberId'] = User::where(['id' => $value['userId']])->value('memberId');
                if($value['memberId']){
                    $memberInfo = Member::where(['id' => $value['memberId']])->find();
                    $value['avatar'] = $memberInfo['avatar'];
                    $value['name'] = $memberInfo['name'];
                }
                unset($value['memberId']);
            }
        }
        $item['joinActivityList'] = $joinActivityList;
        // 是否已报名
        $joinInfo = Joinactivity::where(['activityId' => $activityId, 'userId' => $userId])->find();
        if($joinInfo){
            $isJoin = 1;
        }else{
            $isJoin = 2;
        }
        $item['isJoin'] = $isJoin;

        $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
        if($memberId && $memberId != 0){
            // 组织
            $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
            $item['organization'] = $organization;
        }else{
            $item['organization'] = $this->defaultOrganization;
        }
        unset($item['createOper']);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 提交活动报名
     */
    public function placeActivity()
    {
        $param = self::getHttpParam();

        if (empty($param->activityId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'activityId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->userName)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userName 不能为空');
        }
        if (empty($param->userAvatar)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userAvatar 不能为空');
        }
        if (empty($param->identityNumber)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'identityNumber 不能为空');
        }
        if (empty($param->mobile)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'mobile 不能为空');
        }

        $activityId = $param->activityId;
        $userId = $param->userId;

        $joinactivityInfo = Joinactivity::where(['activityId' => $activityId, 'userId' => $userId])->find();
        if($joinactivityInfo){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '您已报名过，不能再报名');
        }

        //$userName = db('user')->where(['id' => $userId])->value('nickName');
        $data = [
            'id' => BaseHelper::getUUID(),
            'createDate' => time(),
            'activityId' => $activityId,
            'userId' => $userId,
            'userName' => $param->userName,
            'userAvatar' => $param->userAvatar,
            'identityNumber' => $param->identityNumber,
            'mobile' => $param->mobile,
        ];
        $result = Joinactivity::create($data);
        if(!$result){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '提交失败');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '提交成功');
    }

}